﻿using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using UnityEditor;
using UnityEditor.Callbacks;
using UnityEngine;
/// <summary>
/// 拓展工具
/// </summary>
public class ExternalTools
{
    /// <summary>
    /// 文件拓展程序
    /// </summary>
    public class FileExtProcess
    {
        /// <summary>
        /// 文件拓展名
        /// </summary>
        public string FileExts;
        /// <summary>
        /// 应用程序路径
        /// </summary>
        public string Process;

        public FileExtProcess(string fileExt, string pro)
        {
            this.FileExts = fileExt;
            this.Process = pro;
        }
    }

    const string FILE_EXT_KEY = "FILE_EXT_KEY";
    const char SPLIT = '#';//分隔符
    static List<FileExtProcess> _fileExts;

    /// <summary>
    /// 文件打开处理
    /// </summary>
    /// <param name="instanceID"></param>
    /// <param name="line"></param>
    /// <returns></returns>
    [OnOpenAssetAttribute(1)]
    public static bool OpenFileExt(int instanceID, int line)
    {
        Initialize();
        string path = AssetDatabase.GetAssetPath(EditorUtility.InstanceIDToObject(instanceID));
        for (int i = 0; i < _fileExts.Count; i++)
        {
            FileExtProcess fep = _fileExts[i];
            if (string.IsNullOrEmpty(fep.FileExts) || string.IsNullOrEmpty(fep.Process)) continue;//空路径检查
            //正则匹配文件名
            string pattern = string.Format(@".*[{0}]$", fep.FileExts.Replace(',', '|'));
            Match match = Regex.Match(path, pattern);
            if (match.Success)
            {
                string filePath = Application.dataPath + "/" + path.Replace("Assets/", "");
                System.Diagnostics.Process process = new System.Diagnostics.Process();
                System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
                startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
                startInfo.FileName = fep.Process;
                startInfo.Arguments = filePath;
                process.StartInfo = startInfo;
                process.Start();
                return true;
            }
        }
        return false;
    }

    static void Initialize()
    {
        if (_fileExts == null)
        {
            _fileExts = new List<FileExtProcess>();
            if (EditorPrefs.HasKey(FILE_EXT_KEY))
            {
                string[] keys = EditorPrefs.GetString(FILE_EXT_KEY).Split(SPLIT);
                foreach (string key in keys)
                {
                    if (EditorPrefs.HasKey(key))
                        _fileExts.Add(new FileExtProcess(key, EditorPrefs.GetString(key)));
                }
            }
            if (_fileExts.Count == 0) _fileExts.Add(new FileExtProcess(string.Empty, string.Empty));
        }
    }

    [PreferenceItem("文件拓展程序")]
    static void PreferencesGUI()
    {
        Initialize();
        int delIndex = -1;
        EditorGUILayout.HelpBox("设置文件对应打开应用程序，如 [lua,txt] 对应 [Sublime.exe] ", MessageType.Info);
        EditorGUILayout.LabelField("文件拓展程序", EditorStyles.boldLabel);
        GUILayout.BeginHorizontal();
        GUILayout.Box(new GUIContent("拓展名"), GUILayout.ExpandWidth(true));
        GUILayout.Box(new GUIContent("程序路径"), GUILayout.Width(100));
        GUILayout.Label("", GUILayout.Width(90));
        GUILayout.EndHorizontal();
        for (int i = 0; i < _fileExts.Count; i++)
        {
            FileExtProcess fep = _fileExts[i];
            GUILayout.BeginHorizontal();
            fep.FileExts = EditorGUILayout.TextField(fep.FileExts, GUILayout.ExpandWidth(true));
            EditorGUILayout.TextField(fep.Process, GUILayout.Width(100));
            if (GUILayout.Button("Brown", GUILayout.Width(60)))
            {
                string path = Application.dataPath;
                if (!string.IsNullOrEmpty(fep.Process)) path = fep.Process.Substring(0, fep.Process.LastIndexOf('/'));
                path = EditorUtility.OpenFilePanel("指定应用程序", path, "exe");
                if (!string.IsNullOrEmpty(path)) fep.Process = path;
            }
            if (GUILayout.Button("-", GUILayout.Width(25))) delIndex = i;
            GUILayout.EndHorizontal();
        }
        if (delIndex >= 0) _fileExts.RemoveAt(delIndex);
        if (GUILayout.Button("+", GUILayout.Width(60))) { _fileExts.Add(new FileExtProcess(string.Empty, string.Empty)); }

        EditorGUILayout.LabelField("数据", EditorStyles.boldLabel);
        GUILayout.BeginHorizontal();
        if (GUILayout.Button("保存", GUILayout.Width(60))) Save();
        if (GUILayout.Button("清空", GUILayout.Width(60))) Clear();
        GUILayout.EndHorizontal();
    }

    static void Save()
    {
        //保存数据
        StringBuilder extStr = new StringBuilder();
        int count = 0;
        foreach (FileExtProcess fep in _fileExts)
        {
            if (!string.IsNullOrEmpty(fep.FileExts))
            {
                EditorPrefs.SetString(fep.FileExts, fep.Process);
                extStr.AppendFormat("{0}{1}", fep.FileExts, SPLIT);
                count++;
            }
        }
        EditorPrefs.SetString(FILE_EXT_KEY, extStr.ToString());
        EditorUtility.DisplayDialog("提示", string.Format("保存完成{0}条数据", count), "OK");
    }

    static void Clear()
    {
        //清空所有数据
        //if (EditorPrefs.HasKey(FILE_EXT_KEY))
        //{
        //    string[] keys = EditorPrefs.GetString(FILE_EXT_KEY).Split(',');
        //    foreach (string key in keys)
        //        if (EditorPrefs.HasKey(key))
        //            EditorPrefs.DeleteKey(key);
        //}
        EditorPrefs.DeleteAll();
        _fileExts.Clear();
    }
}
